<template>
  <div>
    <el-card>
      <el-row>
        <el-col :span="12">
          <Searchmodule :placeholder="placeholder" @seacherKey="seacher"></Searchmodule>
          <strong></strong>
        </el-col>
        <el-col :span="12" style="text-align: right;">
          <el-button type="primary" icon="el-icon-plus" @click="setDelRole(0)">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :row-style="{height: '10px'}" :cell-style="{padding:'0px'}" :data="rolesList" border stripe
                v-loading="loading">
        <!-- 展开列 -->
        <el-table-column type="expand"   :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-row class="row-border-bottom flex-vcenter" :class="iOne === 0 ? 'row-border-top' : ''"
                    v-for="(itemOne, iOne) in scope.row.resources" :key="itemOne.resourceId">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="deleteRoleResource(scope.row,itemOne.resourceId)">{{ itemOne.resourceName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级，三级权限 -->
              <el-col :span="19">
                <el-row class="flex-vcenter" :class="iTWO === 0 ? '' : 'row-border-top'"
                        v-for="(itemTwo, iTWO) in itemOne.children" :key="itemTwo.resourceId">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="deleteRoleResource(scope.row,itemTwo.resourceId)">
                      {{ itemTwo.resourceName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag v-for="itemThree in itemTwo.children" :key="itemThree.resourceId" type="warning" closable
                            @close="deleteRoleResource(scope.row,itemThree.resourceId)">{{ itemThree.resourceName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="序号" v-if="false" align="center"   :show-overflow-tooltip="true"></el-table-column>
        <!-- expand可展开 -->
        <el-table-column label="角色名称" prop="roleName" align="center"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="角色代码" prop="roleCode" align="center"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="添加时间" prop="createTime" align="center"  :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作" width="400" align="center">
          <template slot-scope="scope">
            <div class="optBtn-box">
              <el-button type="text" icon="el-icon-edit" @click="setDelRole(1, scope.row)">编辑</el-button>
              <el-button type="text" icon="el-icon-delete" :loading="scope.row.isDel"
                         @click="setDelRole(2, scope.row)">删除
              </el-button>
              <el-button type="text" icon="el-icon-setting" @click="setDelRole(3, scope.row)">分配权限
              </el-button>
              <el-button type="text" icon="el-icon-setting" @click="setDelRole(4, scope.row)">添加用户
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style="text-align: center;" :disabled="loading" @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :current-page="queryInfo.pageNo" :page-sizes="[25,50]"
                     :page-size="queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog :append-to-body="true" title="添加角色" :visible.sync="addDialogVisible" width="50%"
               @close="closeDialogVisible(1)">
      <el-form :model="addRolesForm" :rules="formRules" ref="addRolesForm" label-width="70px">
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <!-- <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="addRolesForm.roleDesc"></el-input>
            </el-form-item> -->
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog :append-to-body="true" title="分配权限" :visible.sync="setRightDialogVisible" width="50%"
               @close="closeDialogVisible(3)">
      <!-- default-expand-all默认展开所有节点 -->
      <!--default-expanded-keys 默认勾选的节点的 key 的数组 -->
      <!--  :default-checked-keys="[5]"  -->
      <el-tree
        v-loading="setRight"
        :data="rightsTree"
        show-checkbox
        node-key="resourceId"
        default-expand-all
        :default-checked-keys="defKeys"
        :props="treeProps" ref="treeRef">
      </el-tree>
      <span slot="footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allOtRight()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :append-to-body="true" title="添加用户" :visible.sync="setAddUserRightDialogVisible" width="50%"
               @close="closeDialogVisible(4)">
      <!-- default-expand-all默认展开所有节点 -->
      <!--default-expanded-keys 默认勾选的节点的 key 的数组 -->
      <!--  :default-checked-keys="[5]"  -->

      <el-form :model="submitAddUserForm" ref="submitAddUserForm" label-width="50px">

        <el-form-item prop="userIds"  >

          <el-checkbox-group v-model="submitAddUserForm.userIds">
            <el-checkbox v-for="item in allUserRoles" :label="item.userId"   :key="item.userId" >
              {{item.realName}}
            </el-checkbox>
          </el-checkbox-group>

        </el-form-item>

      </el-form>

      <span slot="footer">
        <el-button @click="setAddUserRightDialogVisible = false  ">取 消</el-button>
        <el-button type="primary" @click="submitAddUser()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  rolePage,
  allResources,
  // findResourcesByRoleId,
  insertRole,
  updateRole,
  assignRoleResource,
  deleteRole,
  deleteRoleResource,
  addUserToRole,
  usersByRoleId
} from '@/api/user.js'
import { mapState } from 'vuex'

let $this = null
export default {
  name: 'rolesManagement',
  computed: {
    ...mapState(['authList'])
  },
  data () {
    return {
      placeholder: '权限名称',
      loading: false,
      queryInfo: {
        pageNo: 1,
        pageSize: 25,
        roleName: ''
      },
      total: 0,
      // 角色列表
      rolesList: [],
      // 显示隐藏添加角色对话框
      addDialogVisible: false,
      // 添加角色的表单数据
      addRolesForm: {},
      // 验证表单
      formRules: {
        roleName: [{
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        }]
      },
      //   显示隐藏分配权限对话框
      setRightDialogVisible: false,
      setRight: false,
      //   加载所有权限树列表
      rightsTree: [],
      //   指定el-tree数据绑定属性
      treeProps: {
        children: 'children',
        label: 'resourceName'
      },
      // 默认选中的节点id值数组
      defKeys: [],
      // 当前操作的角色的id
      roleId: '',
      setAddUserRightDialogVisible: false,
      submitAddUserForm: {
        roleId: '',
        userIds: []
      },
      allUserRoles: []
    }
  },
  created () {
    $this = this
    $this.rolePage()
  },
  methods: {
    authFilter (code) {
      let flag = false
      if (this.authList.length) {
        this.authList.forEach(item => {
          if (item.resourceCode == code) {
            flag = true
          }
        })
      }
      return flag
    },
    // 角色列表
    rolePage () {
      $this.loading = true
      rolePage($this.queryInfo).then(res => {
        $this.loading = false
        if (res.data.code != 200) {
          return $this.$message.error(res.data.message)
        }
        $this.rolesList = res.data.data.records
        $this.total = res.data.data.total
      }).catch(err => {
        $this.loading = false
        return $this.$message.error(err.message)
      })
    },
    handleCurrentChange (val) {
      $this.queryInfo.pageNo = val
      $this.rolePage()
    },
    handleSizeChange (size) {
      $this.queryInfo.pageSize = size
      $this.rolePage()
    },
    seacher (key) {
      $this.queryInfo.roleName = key
      $this.rolePage()
    },
    // 添加角色
    addRoles () {
      $this.$refs.addRolesForm.validate((val) => {
        if (!val) {
          return $this.$message.error('输入有误')
        }
        if ($this.btnId === 0) {
          insertRole($this.addRolesForm).then(res => {
            if (res.data.code != 200) {
              return $this.$message.error(res.data.message)
            }
            $this.rolePage()
            $this.addDialogVisible = false
            return $this.$message.success('添加成功')
          }).catch(err => {
          })
        }
        if ($this.btnId === 1) {
          updateRole($this.addRolesForm).then(res => {
            if (res.data.code != 200) {
              return $this.$message.error(res.data.message)
            }
            $this.rolePage()
            $this.addDialogVisible = false
            return $this.$message.success('修改成功')
          }).catch(err => {
          })
        }
      })
    },
    // 编辑，删除，分配角色权限弹窗
    setDelRole (btnId, row) {
      $this.btnId = btnId
      if (btnId === 1 || btnId === 0) { // 编辑角色
        $this.addDialogVisible = true
        if (btnId === 1) {
          const upUser = {
            roleId: row.id,
            roleName: row.roleName
          }
          $this.addRolesForm = upUser
        }
      }
      if (btnId === 2) { // 删除角色
        $this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return $this.deleteRole(row)
        }).catch(() => {
          return $this.$message.info('已取消删除')
        })
      }
      if (btnId === 3) { // 显示分配权限对话框
        $this.setRight = true
        allResources().then(res => {
          $this.setRight = false
          if (res.data.code != 200) {
            return $this.$message.error(res.data.message)
          }
          $this.setRightDialogVisible = true
          $this.roleId = row.id
          $this.rightsTree = res.data.data
          row.resources.forEach(item => {
            $this.getLeafKeys(item) // 勾选该用户已有权限
          })
        }).catch(err => {
          $this.setRight = false
        })
      }
      if (btnId === 4) { // 显示分配权限对话框
        $this.allUserRoles = []
        $this.submitAddUserForm.userIds = []
        $this.setAddUserRightDialogVisible = true
        $this.submitAddUserForm.roleId = row.id
        usersByRoleId(row.id).then(res => {
          $this.allUserRoles = res.data.data
          $this.allUserRoles.forEach(a => {
            const b = a.selected
            if (b) {
              $this.submitAddUserForm.userIds.push(a.userId)
            }
          })
        })
      }
    },
    submitAddUser () {
      addUserToRole($this.submitAddUserForm).then(res => {
        if (res.data.code != 200) {
          return $this.$message.error(res.data.message)
        }
        $this.setAddUserRightDialogVisible = false
        return $this.$message.success(res.data.message)
      })
    },
    // 删除角色权限
    deleteRoleResource (row, resourceId) {
      const postData = {
        resourceId,
        roleId: row.id
      }

      deleteRoleResource(postData).then(res => {
        if (res.data.code != 200) {
          return $this.$message.error(res.data.message)
        } else {
          console.log('row>>>', row)
          row.resources = res.data.data
          return $this.$message.success('删除成功')
        }
      }).catch(err => {
        return $this.$message.error(err.message)
      })
    },
    // 删除角色
    deleteRole (row) {
      $this.$set(row, 'isDel', true)
      deleteRole(row.id).then(res => {
        $this.$set(row, 'isDel', false)
        if (res.data.code != 200) {
          return $this.$message.error(res.data.message)
        }
        $this.rolePage()
        return $this.$message.success('删除成功')
      }).catch(err => {
        $this.$set(row, 'isDel', false)
      })
    },
    // 分配权限
    allOtRight () {
      // getCheckedKeys 所有选中的节点的key
      // getHalfCheckedKeys  所有半选中的节点的key
      const keys = [
        ...$this.$refs.treeRef.getCheckedKeys(),
        ...$this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const postData = {
        resourceIds: keys,
        roleId: $this.roleId
      }
      assignRoleResource(postData).then(res => {
        $this.rolePage()
      }).catch(err => {
      })
      $this.setRightDialogVisible = false
    },
    // 监听dialog对话框关闭
    closeDialogVisible (dialogId) {
      if (dialogId === 1) { // 重置
        return $this.addRolesForm = {}
      }
      if (dialogId === 3) { // 重置分配权限对话框默认选择
        return $this.defKeys = []
      }
    },
    // 递归获取角色所有权限的id
    getLeafKeys (node) {
      // 当前节点不包含children，则是末级节点
      if (!node.children.length) {
        return $this.defKeys.push(node.resourceId)
      }
      node.children.forEach(item => {
        $this.getLeafKeys(item)
      })
    }
  }
}
</script>
<style scoped lang="scss">
  .el-tag {
    margin: 10px;
  }

  .row-border-top {
    border-top: 1px solid #eee;
  }

  .row-border-bottom {
    border-bottom: 1px solid #eee;
  }

  .flex-vcenter {
    @include display_flex('');
  }
</style>
